package com.cq.hd.merchant.biz;

import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.entity.MerchantAppLoginUser;
import com.cq.hd.common.enums.biz.AutoWithdrawalStateEnum;
import com.cq.hd.common.enums.biz.FinancialAccountTypeEnum;
import com.cq.hd.common.enums.biz.OrderSettleBillTradeTypeEnum;
import com.cq.hd.common.enums.biz.SubOrderStateEnum;
import com.cq.hd.common.utils.LocalDateUtil;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.TbMerchantApi;
import com.cq.hd.member.api.TbWithdrawalBillApi;
import com.cq.hd.member.api.vo.BusinessPageVo;
import com.cq.hd.member.api.vo.MerchantVo;
import com.cq.hd.merchant.vo.MerchantIndexVo;
import com.cq.hd.merchant.vo.MyPageVo;
import com.cq.hd.order.api.TbOrderItemApi;
import com.cq.hd.order.api.TbOrderSettleBillApi;
import com.cq.hd.order.api.dto.OrderItemDto;
import com.cq.hd.order.api.dto.OrderSettleBillDto;
import com.cq.hd.order.api.vo.MerchantOrderAmtStatVo;
import com.cq.hd.order.api.vo.OrderItemVo;
import com.cq.hd.order.api.vo.OrderSettleBillVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Component
@Slf4j
public class IndexBiz {

    @Autowired
    private TbOrderItemApi orderItemApi;

    @Autowired
    private TbMerchantApi merchantApi;

    @Autowired
    private TbBusinessApi businessApi;

    @Autowired
    private TbOrderSettleBillApi orderSettleBillApi;

    @Autowired
    private TbWithdrawalBillApi withdrawalBillApi;

    public MerchantIndexVo statistics(MerchantAppLoginUser merchantAppLoginUser) {
        Long merchantId = merchantAppLoginUser.getMerchantId();

        // 今日核销单量：今天核销的订单数量；
        int verifyOrderNum = 0;
        // 今日核销金额：今天核销的订单，订单分账金额总和；
        BigDecimal verifyOrderAmt = BigDecimal.ZERO;
        // 今日补贴金额：今日核销的订单，补贴金额总和；
        BigDecimal verifySubsidyAmt = BigDecimal.ZERO;
        // 今日总收入：已结算的，今日订单金额+今日补贴金额
        BigDecimal totalAmt = BigDecimal.ZERO;

        String nowStr = LocalDateUtil.toLocalDateToString(LocalDate.now(), Constant.YYYY_MM_DD);

        OrderItemDto orderItemDto = new OrderItemDto();
        orderItemDto.setMerchantId(merchantId);
        orderItemDto.setStartVerifyTime(nowStr + " 00:00:00");
        orderItemDto.setEndVerifyTime(nowStr + " 23:59:59");
        // 查询核销时间=今天，且核销状态=已核销的该商户订单项列表
        orderItemDto.setSubOrderStates(Collections.singletonList(SubOrderStateEnum.VERIFIED.getValue()));
        List<OrderItemVo> orderItemVoList = orderItemApi.listByDto(orderItemDto).unpack();
        if (!CollectionUtils.isEmpty(orderItemVoList)) {
            // 成功下单的订单项列表
            List<OrderItemVo> successOrderItems = new ArrayList<>();

            for (OrderItemVo orderItemVo : orderItemVoList) {
                // 商户订单本金(按比例分配的用户支付的订单款)
                BigDecimal merchantAmt = orderItemVo.getMerchantAmt();
                verifyOrderAmt = verifyOrderAmt.add(merchantAmt);
//                totalAmt = totalAmt.add(merchantAmt);

                // 商户订单补贴(该订单商场补贴的金额)
//                BigDecimal merchantSubsidyAmt = orderItemVo.getMerchantSubsidyAmt();
                BigDecimal totalSubsidyAmt = orderItemVo.getTotalSubsidyAmt();
                verifySubsidyAmt = verifySubsidyAmt.add(totalSubsidyAmt);
//                totalAmt = totalAmt.add(totalSubsidyAmt);

                successOrderItems.add(orderItemVo);
            }

            if (!CollectionUtils.isEmpty(successOrderItems)) {
                // 总订单数
                verifyOrderNum = successOrderItems.size();
            }
        }

        OrderSettleBillDto orderSettleBillDto = new OrderSettleBillDto();
        orderSettleBillDto.setMerchantId(merchantId);
        orderSettleBillDto.setStartTradeTime(nowStr + " 00:00:00");
        orderSettleBillDto.setEndTradeTime(nowStr + " 23:59:59");
        orderSettleBillDto.setTradeTypes(Arrays.asList(OrderSettleBillTradeTypeEnum.MERCHANT_AMT.getValue(), OrderSettleBillTradeTypeEnum.SUBSIDY_AMT.getValue()));
        List<OrderSettleBillVo> orderSettleBillVos = orderSettleBillApi.listByDto(orderSettleBillDto).unpack();
        if (!CollectionUtils.isEmpty(orderSettleBillVos)) {
            for (OrderSettleBillVo orderSettleBillVo : orderSettleBillVos) {
                BigDecimal tradeAmt = orderSettleBillVo.getTradeAmt();
                totalAmt = totalAmt.add(tradeAmt);
            }
        }

        MerchantIndexVo merchantIndexVo = new MerchantIndexVo();
        merchantIndexVo.setVerifyOrderNum(verifyOrderNum);
        merchantIndexVo.setVerifyOrderAmt(verifyOrderAmt);
        merchantIndexVo.setVerifySubsidyAmt(verifySubsidyAmt);
        merchantIndexVo.setTotalAmt(totalAmt);

        return merchantIndexVo;
    }

    public MyPageVo myPage(MerchantAppLoginUser merchantAppLoginUser) {
        // 账户金额=商户本金+补贴金额
        Long merchantId = merchantAppLoginUser.getMerchantId();
        MerchantVo merchantVo = merchantApi.getById(merchantId).unpack();
        BigDecimal balanceAmt = merchantVo.getBalanceAmt();
        BigDecimal subsidyAmt = merchantVo.getSubsidyAmt();

        // 是否是商家
        boolean businessState = false;
        BusinessPageVo businessPageVo = businessApi.getByMobile(merchantVo.getMobile()).unpack();
        if (businessPageVo != null) {
            businessState = true;
        }

        MyPageVo myPageVo = new MyPageVo();
        myPageVo.setFinancialAccountType(merchantVo.getFinancialAccountType());
        myPageVo.setBalanceAmt(balanceAmt);
        myPageVo.setSubsidyAmt(subsidyAmt);
        myPageVo.setTotalAmt(balanceAmt.add(subsidyAmt));
        myPageVo.setBusinessState(businessState);

        MerchantOrderAmtStatVo merchantWaitSettleAmtVo = orderItemApi.getMerchantWaitSettleAmt(merchantId).unpack();
        MerchantOrderAmtStatVo merchantPendingAmt = orderSettleBillApi.getMerchantPendingAmt(merchantId).unpack();

        if (merchantWaitSettleAmtVo != null) {
            // 待结算本金
            myPageVo.setWaitSettleBalanceAmt(merchantWaitSettleAmtVo.getMerchantAmt());
            // 待结算商户补贴
            myPageVo.setWaitSettleSubsidyAmt(merchantWaitSettleAmtVo.getSubsidyAmt());
        }

        if (merchantPendingAmt != null) {
            // 待入账本金 （结算池商户展示）
            if (FinancialAccountTypeEnum.PLATFORM.getValue() == merchantVo.getFinancialAccountType()) {
                myPageVo.setPendingBalanceAmt(merchantPendingAmt.getMerchantAmt());
            }

            // 待入账补贴金额
            myPageVo.setPendingSubsidyAmt(merchantPendingAmt.getSubsidyAmt());
        }

        // 累计入账本金（普通商户展示）
        if (FinancialAccountTypeEnum.SELF.getValue() == merchantVo.getFinancialAccountType()) {
            myPageVo.setAccBalanceAmt(withdrawalBillApi.getMerchantAccWithdrawalAmt(merchantId).unpack());
            myPageVo.setProgressingWithdrawAmt(withdrawalBillApi.sumAutoWithdrawalAmount(merchantId, AutoWithdrawalStateEnum.ALREADY.getValue()).unpack());
        }

        return myPageVo;
    }
}
